package br.inf.solutions.apresentacoes.ssp.control;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import br.com.vexillum.util.HibernateUtils;
import br.com.vexillum.util.Return;
import br.inf.solutions.apresentacoes.ssp.model.PostGraduation;

@Service
@Scope("prototype")
public class PostGraduationController extends BaseController<PostGraduation> {

	public PostGraduationController() {
		super(PostGraduation.class);
	}	
	
	@Override
	public Return save() {
//		Return ret = new Return(true);
//		List<PostGraduation> allList = (List<PostGraduation>) listAll().getList();
//		
//		for(PostGraduation post : allList){
//			if(post.getPattern().equals(entity.getPattern())){
//				post.setPattern(entity);
//				ret.concat(update(post));
//				break;
//			}
//		}
//		return ret;
		return super.save();
	}
	
	@SuppressWarnings("unchecked")
	public Return sortListByPattern(){
		Return ret = new Return(true);
		List<PostGraduation> allList = (List<PostGraduation>) listAll().getList();
		List<PostGraduation> sortedAllList = new ArrayList<>();
		
		List<PostGraduation> listEntity = (List<PostGraduation>) HibernateUtils.initialize(data.get("listEntity"));
		List<PostGraduation> sortedList = new ArrayList<>();
		
		HibernateUtils.initialize(listEntity);
		
		PostGraduation pattern = null;
		while(allList.size() > 0){
			for(Iterator<PostGraduation> i = allList.iterator(); i.hasNext();){
				PostGraduation post = i.next();
				post = HibernateUtils.materializeProxy(post);
				if(post.getPattern() == null || post.getPattern().equals(pattern)){
					sortedAllList.add(post);
					pattern = post;
					i.remove();
					break;
				}
			}
		}
		
		for(PostGraduation post : sortedAllList){
			for(PostGraduation post2 : listEntity){
				if(post.equals(post2)){
					sortedList.add(post);
					break;
				}
			}
		}
		
		ret.setList(sortedList);
		
		return ret;
	}
	
	public PostGraduation getPattern(PostGraduation post){
		String sql = "SELECT pattern FROM PostGraduation p WHERE p.id = " + post.getId();
		getData().put("sql", sql);
		return (PostGraduation) searchByHQL().getList().get(0);
	}
	
}
